import {BrowserWindow, ipcMain} from "electron";

type InitOptions = {
    isOther: boolean
}

// 为窗口注册事件
export const initializeDOMListeners: (win: BrowserWindow, options?: InitOptions) => void = (win: BrowserWindow, opt) => {
    // 关闭——主窗口最小化到托盘
    ipcMain.on(`set-close-window-${win.id}`, () => {
        // 根据配置来决定是否销毁当前窗口
        const focusWindow = getFocusedWindow()
        if (opt?.isOther) {
            focusWindow?.destroy()
            focusWindow?.removeAllListeners()
        } else {
            focusWindow?.hide()
            focusWindow?.close()
            // focusWindow?.setSkipTaskbar(true)
        }
    })

    // 将窗口最大化
    ipcMain.on(`set-max-window-${win.id}`, () => {
        const focusWindow = getFocusedWindow()
        console.log('is Max?', focusWindow?.isMaximized())
        if (focusWindow?.isMaximized()) {
            focusWindow?.unmaximize()
        } else {
            focusWindow?.maximize()
            focusWindow?.setMinimumSize(670, 400)
        }
    })

    // 最小化到任务栏
    ipcMain.on(`set-mini-window-${win.id}`, () => {
        const focusWindow = getFocusedWindow()
        focusWindow?.minimize()
    })

    // 打开控制台
    ipcMain.on('open-devtools', () => {
        const focusWindow = BrowserWindow.getFocusedWindow()
        if (focusWindow && !focusWindow.webContents.isDevToolsOpened()) {
            focusWindow.webContents.openDevTools()
        } else {
            focusWindow?.webContents.closeDevTools()
        }
    })
}

function getFocusedWindow() {
    return BrowserWindow.getFocusedWindow()
}